package com.sky.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderDetailVO;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private   OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //1.业务异常（地址簿没有数据，购物车没有数据）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        ShoppingCart shoppingCart = new ShoppingCart();
        Long userid = BaseContext.getCurrentId();
        shoppingCart.setUserId(userid);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.select(shoppingCart);

        if(shoppingCartList.size()==0){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2.插入一条订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);//支付状态（未支付）
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态（待付款）
        orders.setPhone(addressBook.getPhone());//手机号
        orders.setUserId(userid);//用户id
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号（当前系统时间的时间戳）
        orders.setConsignee(addressBook.getConsignee());//收货人
        //地址使用字符串拼装
        String address = addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName();
        orders.setAddress(address);
        //查询当前用户名字
        User user = userMapper.getById(userid);
        orders.setUserName(user.getName());
        orderMapper.insert(orders);

        //3.插入多条订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
            orderDetailMapper.insert(orderDetailList);//直接插入list集合，进行批量插入

        //4.清空购物车
        shoppingCartMapper.deleteAll(shoppingCart);
        //5.封装VO结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr = RandomStringUtils.randomNumeric(32);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("timeStamp", timeStamp);
        jsonObject.put("nonceStr", nonceStr);
        jsonObject.put("package", "prepay_id=xxxxxxxxxx");
        jsonObject.put("signType", "RSA");
        jsonObject.put("paySign", "packageSign");
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);

        //通过websocket实现来单提醒,向客户端浏览器推送消息 type orderId content
        //使用map进行封装
        Map map = new HashMap();
        map.put("type",1);//提醒类型：1表示来单提醒 2表示客户催单
        map.put("orderId",orders.getId());//订单id
        map.put("content","订单号："+outTradeNo);//订单号
        //转换成json格式
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public OrderDetailVO getOrderDetailById(String id) {
        //根据订单id查询订单
        Orders orders = orderMapper.getById(id);
        //根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //封装
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        BeanUtils.copyProperties(orders, orderDetailVO);
        orderDetailVO.setOrderDetailList(orderDetailList);

        return orderDetailVO;
    }


    //分页查询历史订单
    @Override
    public PageResult getHistoryOrder(OrdersPageQueryDTO ordersPageQueryDTO) {

        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);

        //开始分页查询,第一个是页码，第二个是每页显示记录数
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //调用mapper方法，必须使用Page类来接收返回值
        Page<OrderDetailVO> page = orderMapper.PageQuerySelect(ordersPageQueryDTO);
        for (OrderDetailVO orderDetailVO : page) {
            Long orderId =  orderDetailVO.getId();
            orderDetailVO.setOrderDetailList(orderDetailMapper.getByOrderId(String.valueOf(orderId)));
        }
        //通过page获取
        long total = page.getTotal();
        List<OrderDetailVO> list = page.getResult();
        return new PageResult(total,list);
    }
    //取消订单
    @Override
    public void cancelOrderById(String id) {
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void repetitionOrder(String id) {
        //根据id查询订单
        //Orders orders = orderMapper.getById(id);
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        //根据订单数据，再进行插入数据
        Long userId = BaseContext.getCurrentId();
        for (OrderDetail orderDetail : detailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setUserId(userId);
            shoppingCart.setDishId(orderDetail.getDishId());
            shoppingCart.setSetmealId(orderDetail.getSetmealId());
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    @Override
    public OrderStatisticsVO getStatistics() {
        //获取数量
        Integer confirmed = orderMapper.getConfirmed();
        Integer deliveryInProgress= orderMapper.getDeliveryInProgress();
        Integer toBeConfirmed  = orderMapper.getToBeConfirmed();
        //封装
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

    @Override
    public PageResult getPageOrder(OrdersPageQueryDTO ordersPageQueryDTO) {

        //开始分页查询,第一个是页码，第二个是每页显示记录数
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //调用mapper方法，必须使用Page类来接收返回值
        Page<OrderDetailVO> page = orderMapper.PageAdminOrder(ordersPageQueryDTO);
        //插入订单详细数据
        for (OrderDetailVO orderDetailVO : page) {
            //获取订单详细里面的数据
            Long orderId =  orderDetailVO.getId();
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(String.valueOf(orderId));
            //菜品名字封装

            StringBuilder OrderDishes = new StringBuilder();
            for (OrderDetail orderDetail : orderDetailList) {
                OrderDishes.append(orderDetail.getName()).append(".");
            }
            orderDetailVO.setOrderDishes(OrderDishes.toString());
        }
        //通过page获取
        long total = page.getTotal();
        List<OrderDetailVO> list = page.getResult();
        return new PageResult(total,list);
    }

    //接单
    @Override
    public void updateStatus(Orders orders) {
        orderMapper.update(orders);
    }

    /**
     * 催单功能
     * @param id
     */
    @Override
    public void reminder(String id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);
        if(orders==null){
            throw new RuntimeException(MessageConstant.ORDER_NOT_FOUND);
        }
        //map封装
        Map map = new HashMap<>();
        map.put("type",2);//提醒类型：1表示来单提醒 2表示客户催单
        map.put("orderId",orders.getId());//订单id
        map.put("content","订单号："+orders.getNumber());//订单号
        //转换成json格式
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
